<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>vue-hotel</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="robots" content="all,follow">
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/style.default.css" id="theme-stylesheet">
    <link id="new-stylesheet" rel="stylesheet">
    <style>
        @media screen and (max-width: 444px) {
            #video {
                width: 320px;
            }
        }
    </style>
</head>

<body>
<div id="container" class="page login-page">
    <div class="container d-flex align-items-center">
        <div class="form-holder has-shadow">
            <div class="row">
                <!-- Logo & Information Panel-->
                <div class="col-lg-6">
                    <div id="face_window" class="info d-flex align-items-center">
                        <div class="content">
                            <div class="logo">
                                <h1>欢迎登录</h1>
                            </div>
                            <a style="color: white;text-decoration: none" href="/"><p>高级软件工程实训课</p></a>
                        </div>
                    </div>
                </div>
                <!-- Form Panel    -->
                <div class="col-lg-6 bg-white">
                    <div class="form d-flex align-items-center">
                        <div class="content">
                            <video id="video" width="460" autoplay="autoplay" style="display: none;"></video>
                            <form method="post" action="#" class="form-validate" id="loginFrom" novalidate="novalidate">
                                <div class="form-group">
                                    <input id="login-username" type="text" name="userName" required="" data-msg="请输入用户名"
                                           placeholder="用户名" class="input-material">
                                </div>
                                <div class="form-group">
                                    <input id="login-password" type="password" name="passWord" required=""
                                           data-msg="请输入密码"
                                           placeholder="密码" class="input-material">
                                </div>
                                <button id="login" type="button" onclick="submit_login()" class="btn btn-primary">登录
                                </button>
                                <div style="margin-top: -40px;">
                                    <div class="custom-control custom-checkbox " style="float: right;">
                                        <input type="checkbox" class="custom-control-input" id="check1">
                                        <label class="custom-control-label" for="check1">记住密码</label>
                                    </div>
                                </div>
                            </form>
                            <br>
                            <button id="change-model" onclick="change_hide()" type="button" class="btn btn-primary">
                                智能人脸登录
                            </button>
                            <small>没有账号?</small><a href="/user/register" class="signup">&nbsp;注册</a>
                            <canvas id="canvas" width="460" height="345" style="display: none;"></canvas>
                            <div id="login-info" class="alert alert-info"
                                 style="margin-top: 10px ;display: none; width: 82%">账号或密码错误
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- JavaScript files-->
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery.validate.min.js"></script>
<!--表单验证-->
<!-- Main File-->
<script src="js/front.js"></script>

<script>
    let isOpen = false;
    let intervalID; //定时任务id
    function submit_login() {
        console.log('登录');
        let username = $('#login-username').val();
        let password = $('#login-password').val();
        let info = $('#login-info');
        if (username.length >0) {
            info.css("display", "block");
            info.text("用户名不能为空,且不低于六位");
        }
        if (password.length <= 3) {
            info.css("display", "block");
            info.text("密码不能为空");
        }
        if (username.length > 0 && password.length > 3) {
            info.css("display", "none");
            $.ajax({
                type: "POST",
                url: "/user/login/",
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
                },
                dataType: 'json',
                data: {
                    "username": username,
                    "password": password
                },
                success: function (result) {
                    let res = result;
                    info.css("display", "block");
                    if (res.code === 1) {
                        info.text("登录成功,正在跳转...");
                        setTimeout(function () {
                            let next=getQueryVariable('next');
                            window.location = next;
                        }, 2000)
                    } else {
                        console.log(result)
                        info.text("登录失败，请检查后重试！");
                    }
                },
                error: function (e) {
                    console.log(e.status);
                    console.log(e.responseText);
                }
            });
        }
    }

    function open_video() {
        let video = document.getElementById("video");
        // 老的浏览器可能根本没有实现 mediaDevices，所以我们可以先设置一个空的对象
        if (navigator.mediaDevices === undefined) {
            navigator.mediaDevices = {};
        }
        // 一些浏览器部分支持 mediaDevices。我们不能直接给对象设置 getUserMedia
        // 因为这样可能会覆盖已有的属性。这里我们只会在没有getUserMedia属性的时候添加它。
        if (navigator.mediaDevices.getUserMedia === undefined) {
            navigator.mediaDevices.getUserMedia = function (constraints) {
                // 首先，如果有getUserMedia的话，就获得它
                var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
                // 一些浏览器根本没实现它 - 那么就返回一个error到promise的reject来保持一个统一的接口
                if (!getUserMedia) {
                    return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
                }
                // 否则，为老的navigator.getUserMedia方法包裹一个Promise
                return new Promise(function (resolve, reject) {
                    getUserMedia.call(navigator, constraints, resolve, reject);
                });
            }
        }
        //默认使用前摄像头，强制使用后置摄像头如下设置
        // let constraints = {video: { facingMode: { exact: "environment" } }};
        let constraints = {video: true};
        navigator.mediaDevices.getUserMedia(constraints)
            .then(function (stream) {
                // 旧的浏览器可能没有srcObject
                if ("srcObject" in video) {
                    video.srcObject = stream;
                } else {
                    // 防止在新的浏览器里使用它，因为它已经不再支持了
                    video.src = window.URL.createObjectURL(stream);
                }
                video.onloadedmetadata = function (e) {
                    video.play();
                };
            })
            .catch(function (err) {
                console.log(err.name + ": " + err.message);
            });
    }

    //拍照
    function get_photo() {
        let video = document.getElementById("video");
        let canvas = document.getElementById("canvas");
        let context = canvas.getContext("2d");
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        return canvas.toDataURL("image/jpg");
    }

    function postImg() {
        let img = get_photo();
        let info = $('#login-info');
        $.ajax({
            type: "POST",
            url: "/user/face_check/",
            beforeSend: function (xhr) {
                xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
            },
            dataType: 'json',
            data: {
                "id": 0,
                "faceImg": img
            },
            success: function (result) {
                console.log(result);
                let res = result;
                info.css("display", "block");
                if (res.code === 1) {
                    info.text("人脸验证成功,正在跳转...");

                    //成功了就关闭任务
                    clearInterval(intervalID);
                    setTimeout(function () {
                        let next=getQueryVariable('next');
                        window.location = next;
                        {#window.location.href= "http://192.168.124.16:8080/#/index"#}
                    }, 2000)

                } else {
                    info.html("登录失败，正在继续尝试，请不要关闭摄像头！");
                }
            },
            error: function (e) {
                console.log(e.status);
                console.log(e.responseText);
            }
        });
    }

    function getQueryVariable(variable) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (pair[0] == variable) {
                return pair[1];
            }
        }
        return "/user/home/";
    }

    function change_hide() {
        let loginFrom = $("#loginFrom")[0];
        let video = $("#video")[0];
        let change_button = $("#change-model");
        let style = video.style.display;
        if (style != "none") {
            //密码登录
            loginFrom.style.display = "block";
            video.style.display = "none";
            change_button.text("智能人脸登录");
            //关闭定时post任务
            clearInterval(intervalID);
        } else {
            //人脸登录
            loginFrom.style.display = "none";
            video.style.display = "block";
            change_button.text("账号密码登录");
            if (!isOpen) {
                open_video();
            }
            isOpen = true;
            //setTimeout(postImg, 2000); //给2s的时间去调整，然后再捕获照片
            intervalID = setInterval(postImg, 2000); //2s周期循环执行任务
        }
    }

</script>

</body>

</html>